"""
一、数据来源分析
    - 需求分析
        获取“热门视频榜单”的每个视频对应的弹幕。
    - 接口分析
        1、热门视频榜单URL = https://api.bilibili.com/x/web-interface/popular?ps=20&pn={page}
        2、弹幕URL = https://api.bilibili.com/x/v2/dm/web/history/seg.so?type=1&oid=1201036299&date=2023-07-18
"""
import requests

# 这个库是google的protobuf数据序列化库，其中的text_format是解决中文编码问题的
# 需要 pip install protobuf 来安装
import google.protobuf.text_format as text_format

# my_pd2是B站的protobuf序列化规则，是在网上找到的。
# 它的作用是定义如何将序列化好的弹幕变成正常的字符串
import my_pd2


# 获取B站弹幕的seg.so文件，其本质是protobuf数据序列化格式的二进制文件
def get_danmu_seg(url, headers, params, cookies):

    resp = requests.get(url=url, headers=headers, params=params, cookies=cookies)
    return resp.content


# 反序列化，将序列化的数据 ==> 转成字符串
def parse_protobuf(data):
    my_seg = my_pd2.DmSegMobileReply()
    my_seg.ParseFromString(data)
    for item in my_seg.elems:
        text = text_format.MessageToString(item, as_utf8=True)
        print(text)


def main():
    url = 'https://api.bilibili.com/x/v2/dm/web/history/seg.so'
    headers = {
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.43',
        'Origin': 'https://www.bilibili.com',
        'Referer': 'https://www.bilibili.com/',
    }
    cookies = {
        "LIVE_BUVID": "AUTO3415877792569142",
        "DedeUserID": "52119634",
        "DedeUserID__ckMd5": "67e45da9cb8ce297",
        "CURRENT_BLACKGAP": "0",
        "i-wanna-go-back": "-1",
        "buvid_fp_plain": "undefined",
        "blackside_state": "0",
        "nostalgia_conf": "-1",
        "hit-dyn-v2": "1",
        "is-2022-channel": "1",
        "dy_spec_agreed": "1",
        "buvid4": "8DF6455F-9DB6-5B76-C999-9361A1668EA994844-022012119-1qniOG9rIRY%2Fq4pNehqo5g%3D%3D",
        "fingerprint3": "e127d5c7c70adb8cabeb0c21c46b5965",
        "rpdid": "|(J~luuYR|lY0J'uY~uk)km~u",
        "b_ut": "5",
        "CURRENT_FNVAL": "4048",
        "CURRENT_PID": "54b56d40-cd4f-11ed-a16a-11b7c1a69876",
        "header_theme_version": "CLOSE",
        "buvid3": "C10617D6-255C-F826-F378-CAA5365E192620201infoc",
        "b_nut": "1682434120",
        "_uuid": "AE3F910AE-1677-1F52-10723-987EC1010D1099F44565infoc",
        "FEED_LIVE_VERSION": "V8",
        "fingerprint": "8e6599ec5b0fb846902bda3d0100fc00",
        "buvid_fp": "8e6599ec5b0fb846902bda3d0100fc00",
        "PVID": "1",
        "SESSDATA": "9e4ca6fc%2C1705102468%2Cb0eba%2A71ZfgjBNSSUvDB3VTTRgCL0VAIxlDjWZf2_ZweeL2C2L4mpUtdAf4vgd8wna84GWRcxMOjzQAAIgA",
        "bili_jct": "2915d1475be6ebeca9be8528965961c2",
        "sid": "7ms15n7l",
        "CURRENT_QUALITY": "0",
        "hit-new-style-dyn": "1",
        "b_lsid": "5E61E9E5_1896D0C85E6",
        "bp_video_offset_52119634": "819966903866884100",
        "home_feed_column": "5",
        "browser_resolution": "2558-1297"
    }
    params = {
        'type': '1',            # 弹幕类型（必须）
        'oid': '1200965608',    # 视频cid（必须）
        'date': '2023-07-19',   # 弹幕日期（必须）
    }
    data = get_danmu_seg(url, headers, params, cookies)
    parse_protobuf(data)


if __name__ == '__main__':
    main()
